package cn.edu.swu.cly.repo;

import org.apache.commons.dbcp2.BasicDataSource;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.List;

public class DatabaseService {
    //连接数据库的service，这个类下的内容值关乎database的连接
    //设置连接池与断开连接
    public final static String CONTEXT_KEY = "DATABASE_SERVICE";
    private static BasicDataSource dataSource = null;

    private DatabaseService() {}

    private static DatabaseService instance = new DatabaseService();            //********没太懂这个

    public static DatabaseService getInstance() {return instance;}

    //数据库初始化连接
    public void init() {
        dataSource = new BasicDataSource();

        //连接数据库
        dataSource = new BasicDataSource();
        dataSource.setDriverClassName("com.mysql.cj.jdbc.Driver");
        dataSource.setUrl("jdbc:mysql://127.0.0.1:3306/bookstore");
        dataSource.setUsername("root");
        dataSource.setPassword("cai20060215");

        //连接池的配置
        dataSource.setInitialSize(3);          //初始连接
        dataSource.setMaxIdle(4);              //最大空闲
        dataSource.setMaxTotal(6);             //最大连接数
        dataSource.setMinIdle(2);              //最小空闲连接数
//      dataSource.setMaxWaitMillis(10000);     // 取连接最大等待时间（毫秒）
    }

    private Connection getConnection() throws SQLException {
        return dataSource.getConnection();
    }

    //同构一个方法
    public void closeDataSource() {
        //
        if(dataSource != null) {
            try {
                dataSource.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }

    //服务器连接请求，处理String sql语句
    public List query(String sql, ResultSetVisitor visitor) throws SQLException {       //请求处理
        try(Connection connection = this.dataSource.getConnection()) {
            try (Statement statement = connection.createStatement()) {
                try (ResultSet resultSet = statement.executeQuery(sql)) {              //execute
                    return visitor.visit(resultSet);
                }
            }
        }
    }

    public boolean execute(String sql) throws SQLException {        //执行请求(为什么这里不用ResultSet)
        try(Connection connection = this.dataSource.getConnection()) {
            try(Statement statement = connection.createStatement()) {
                return statement.execute(sql);
            }
        }
    }
}
